/**
 * COPYRIGHT. Harry Wu 2011. ALL RIGHTS RESERVED.
 * Project: just
 * Author: Harry Wu <harrywu304@gmail.com>
 * Created On: May 30, 2011 5:28:28 PM
 *
 */
package org.justframework.server;

import org.justframework.ext.zeroc.impl.ZerocRpcImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import Ice.Communicator;
import Ice.InitializationData;
import Ice.ObjectAdapter;
import Ice.Properties;
import Ice.ServantLocator;
import Ice.Util;

/**
 * @author whx
 * 
 */
public class IceServer {

	/**
	 * Ice.Communicator
	 */
	private Communicator ic = null;

	/**
	 * rpc代理适配器
	 */
	private ObjectAdapter adapter = null;

	/**
	 * 服务定位器
	 */
	private ServantLocator servantLocator = null;

	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(IceServer.class);

	public static void main(String[] args) {
		logger.info("IceServer starting...");
		IceServer server = new IceServer();
		server.startup();
	}

	private void startup() {
		int status = 0;
		try {
			Properties prop = Util.createProperties();
			prop.setProperty("Ice.MessageSizeMax", "1024");
			prop.setProperty("Ice.ThreadPool.Server.Size", "10");
			prop.setProperty("Ice.ThreadPool.Server.SizeMax", "500");
			prop.setProperty("Ice.ThreadPool.Server.SizeWarn", "480");
			prop.setProperty("Ice.TCP.RcvSize", "65535");
			prop.setProperty("Ice.TCP.SndSize", "65535");
			
			// 初始化Ice.Communicator对象
			InitializationData initData = new InitializationData();
			initData.properties = prop;
			ic = Ice.Util.initialize(initData);
			// 初始化ICE通信服务
			Ice.ObjectAdapter adapter = ic.createObjectAdapterWithEndpoints(
					"ZeroRpcAdapter", "tcp -p 15212");

			// 模式一：添加ICE服务
			Ice.Object object = new ZerocRpcImpl();
			adapter.add(object, Ice.Util.stringToIdentity("ZeroRpc"));

			// 模式二：添加自定义servant locator
			// adapter.addServantLocator(new AppServantLocator(), "");

			// 启动ICE服务
			adapter.activate();
			ic.waitForShutdown();
		} catch (Exception e) {
			e.printStackTrace();
			status = 1;
		} finally {
			if (ic != null) {
				ic.destroy();
			}
		}
		System.exit(status);
	}
	
	/**
	 * 关闭服务器
	 */
	private void shutdown() {
		adapter.deactivate();
		adapter.destroy();
		ic.destroy();	
	} 

}
